﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Spring.IO;
using Spring.Social.Dropbox.Api;
using Spring.Social.Dropbox.Connect;

namespace WebChat.Services.Controllers
{
    public class DropBoxController : ApiController
    {
        private string AppKey = "k77puackhmmd758";
        private string AppSecret = "edv57ugh25fwytu";
        private string ClientAppKey = "zd1ovuvrce8lli0m";
        private string ClientAppSecret = "tvnx899pfh5l0m4";

        [HttpPost]
        public HttpResponseMessage Post()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/App_Data/" + postedFile.FileName);//not partially correct because it saves file to da db of appharbour
                    postedFile.SaveAs(filePath);

                    docfiles.Add(DropboxShareFile(filePath, postedFile.FileName));
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            return result;
        }

        private string DropboxShareFile(string path, string filename)
        {
            DropboxServiceProvider dropboxServiceProvider =
                new DropboxServiceProvider(this.AppKey, this.AppSecret, AccessLevel.AppFolder);
            IDropbox dropbox = dropboxServiceProvider.GetApi(this.ClientAppKey, this.ClientAppSecret);

            Entry uploadFileEntry = dropbox.UploadFile(
                new FileResource(path), filename);

            var sharedUrl = dropbox.GetMediaLink(uploadFileEntry.Path);
            return (sharedUrl.Url + "?dl=1"); // we can download the file directly
        }
    }
}
